<template>
  <div class="owner-view">
    <el-card class="user-card" shadow="hover">
      <div class="profile-header">
        <el-avatar
          :size="80"
          class="user-avatar"
          :src="loginPerson.img"
        ></el-avatar>
        <div class="user-meta">
          <h2 class="username">{{ loginPerson.username }}</h2>
          <el-tag
            :type="loginPerson.customer_type === 'user' ? 'success' : 'warning'"
            effect="dark"
          >
            {{
              loginPerson.customer_type === "user" ? "普通用户" : "认证供应商"
            }}
          </el-tag>
        </div>
      </div>

      <el-divider></el-divider>

      <div class="profile-body">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <i class="el-icon-mobile-phone"></i>
              <span class="label">联系方式：</span>
              <span class="value">{{ loginPerson.phone }}</span>
            </div>
            <div class="info-item">
              <i class="el-icon-location-outline"></i>
              <span class="label">所在地区：</span>
              <span class="value">{{ loginPerson.address }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <i class="el-icon-date"></i>
              <span class="label">登录时间</span>
              <span class="value">{{ loginTime }}</span>
            </div>
            <div class="info-item">
              <i class="el-icon-document"></i>
              <span class="label">账户安全：</span>
              <el-rate
                :value="3"
                disabled
                show-text
                text-color="#ff9900"
              ></el-rate>
            </div>
          </el-col>
        </el-row>
      </div>

      <el-divider></el-divider>

      <div class="profile-actions">
        <el-button type="primary" icon="el-icon-edit" @click="editProfile"
          >编辑资料</el-button
        >
        <el-button type="danger" icon="el-icon-switch-button" @click="logout"
          >退出登录</el-button
        >
      </div>
    </el-card>
    <el-dialog
      title="编辑资料"
      :visible.sync="editDialogVisible"
      width="40%"
      @closed="resetForm"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" />
        </el-form-item>

        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>

        <el-form-item label="所在地区" prop="address">
          <el-input v-model="editForm.address" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" type="password" show-password />
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "OwnerView",
  data() {
    return {
      editDialogVisible: false,
      editForm: {
        username: "",
        phone: "",
        address: "",
      },
      editRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入联系方式", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确" },
        ],
        address: [
          { required: true, message: "请输入所在地区", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapState({
      loginPerson: (state) =>
        state.loginPerson || JSON.parse(localStorage.getItem("loginPerson")), // 从 Vuex 或 localStorage 获取
    }),
    loginTime() {
      return JSON.parse(localStorage.getItem("loginTime"));
    },
  },
  methods: {
    logout() {
      this.$store.commit("SET_LOGIN_PERSON", null);
      localStorage.removeItem("loginTime");
      localStorage.removeItem("loginPerson");
      this.$router.push("/login");
    },
    editProfile() {
      // 保留原始img和id
      this.editForm = {
        ...JSON.parse(JSON.stringify(this.loginPerson)),
        username: this.loginPerson.username,
        phone: this.loginPerson.phone,
        address: this.loginPerson.address,
      };
      this.editDialogVisible = true;
    },

    resetForm() {
      this.$refs.editForm.resetFields();
    },

    async submitEdit() {
      try {
        await this.$refs.editForm.validate();

        // 构造更新数据（保留原始img和id）
        const updatedData = {
          ...this.loginPerson, // 保留原始数据
          ...this.editForm, // 覆盖可修改字段
        };

        // 根据用户类型选择更新模块
        const module =
          this.loginPerson.customer_type === "user" ? "user" : "supplier";

        // 分发到Vuex action
        await this.$store.dispatch(
          `${module}/update${module.charAt(0).toUpperCase() + module.slice(1)}`,
          updatedData
        );

        // 更新全局登录状态
        this.$store.commit("SET_LOGIN_PERSON", updatedData, { root: true });

        this.$message.success("资料更新成功");
        this.editDialogVisible = false;
      } catch (error) {
        console.error("保存失败:", error);
      }
    },
  },
};
</script>

<style scoped>
.owner-view {
  padding: 40px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  min-height: 100vh;
}

.user-card {
  max-width: 800px;
  margin: 0 auto;
  border-radius: 16px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.profile-header {
  display: flex;
  align-items: center;
  padding: 20px 0;
}

.user-avatar {
  margin-right: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.user-meta {
  flex: 1;
}

.username {
  font-size: 28px;
  color: #2d3436;
  margin-bottom: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  font-size: 16px;
  border-bottom: 1px solid #eee;
}

.info-item i {
  width: 30px;
  font-size: 20px;
  color: #409eff;
}

.label {
  color: #666;
  min-width: 80px;
}

.value {
  color: #2d3436;
  flex: 1;
}

.profile-actions {
  text-align: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .owner-view {
    padding: 20px;
  }

  .profile-header {
    flex-direction: column;
    text-align: center;
  }

  .user-avatar {
    margin-right: 0;
    margin-bottom: 20px;
  }
}
</style>
